package com.lzj.framework.security;

import cn.hutool.core.util.StrUtil;
import com.lzj.common.core.domain.R;
import com.lzj.common.utils.JsonUtils;
import com.lzj.common.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author 贱贱
 * @Description 认证失败处理器, Security认证失败的时候会调用这个commence方法
 * @Date 2024/07/11 15:48
 */
@Component("unauthorizedHandler")
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 未认证状态码
        int failedCode = HttpServletResponse.SC_UNAUTHORIZED;
        R<String> msg = R.fail(failedCode, StrUtil.format(" 请求访问：{}，认证失败， 无法访问系统资源", request.getRequestURI()));
        ServletUtils.renderString(response, JsonUtils.toJsonString(msg));
    }
}
